package com.greatchn.no_session_auth_code.config;

import cn.hutool.core.util.StrUtil;
import com.greatchn.no_session_auth_code.web.po.Menu;
import com.greatchn.no_session_auth_code.web.srv.MenuSrv;
import org.springframework.core.annotation.Order;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;

/**
 * @FilterMetadataSource: 设置角色权限
 * @author: ZBoHang
 * @time: 2023/2/9 16:50
 */
@Order
@Component
public class FilterMetadataSource implements FilterInvocationSecurityMetadataSource {

    @Resource
    private MenuSrv menuSrv;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) {
        //获取请求的url
        String requestUrl = ((FilterInvocation) object).getRequestUrl();

        List<Menu> menuList = menuSrv.getAllMenu();

        for (Menu menu : menuList) {
            //判断请求的url是否在菜单角色是否匹配
            // 返回菜单所能够访问的角色
            if(antPathMatcher.match(menu.getMenuPath(),requestUrl)){

                String[] strArr = StrUtil.splitToArray(menu.getAvailableRoles(), StrUtil.COMMA);
                return SecurityConfig.createList(strArr);
            }
        }
        //没匹配的url 无相应权限访问
        return SecurityConfig.createList("无相应权限访问!");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return false;
    }
}
